package backend.task;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import backend.DefaultConf;

/**
 * A global table maintains runtime tasks status.
 * 
 * @author wuhao
 *
 */
public class TaskContext {

	private final static Map<String, FileTask> workingTasks = new ConcurrentHashMap<String, FileTask>();
	private static Thread flushThread = null;
	private final static File target = new File(DefaultConf.dumpTaskFile);
	private static Logger logger = Logger.getLogger(TaskContext.class.getName());
	
	
	public final static void putTask(String uuid, FileTask task) {
		workingTasks.put(uuid, task);
	}

	public final static void removeTask(String key) {
		workingTasks.remove(key);
	}
	
    public final static Map<String, FileTask> getContext(){
    	return workingTasks;
    }
    
//    public final static Date getLastTime(){
//    	
//    	Date dummy = new Date(0);
//    	if(workingTasks.size() == 0){
//    		return dummy;
//    	}
//    	else{
//    		for(Entry<String, FileTask> entry : workingTasks.entrySet()){
//    			File f = entry.getValue().getFile();
//    			if(f.exists()){
//    				dummy = FileUtils.isFileNewer(f, dummy)?new Date(f.lastModified()):dummy;
//    			}
//    		}
//    		logger.warn("The most recent file lastm is " + dummy);
//    		return dummy;
//    	}
//    }
    
    public final static void flushContext(){
    	
    	PrintWriter pw = null;
		try {
			pw = new PrintWriter(new FileOutputStream(target, false), false);
		} catch (FileNotFoundException e) {
			logger.error(e);
		}
    	
    	for (Entry<String, FileTask> entry : workingTasks
				.entrySet()) {
			if(!entry.getValue().getFile().exists()){
				continue;
			}
			StringBuilder sb = new StringBuilder();
			FileTask task = entry.getValue();
			sb.append(task.getStatus()).append(" ");
			sb.append(task.getFile().getAbsolutePath()).append(" ");
			sb.append(task.getLastReadLine()).append("\n");
			pw.write(sb.toString());
			pw.flush();
		}
		pw.close();
    }

	public final static void startContextJob() throws IOException {
		
		if (flushThread != null) {
			flushThread.interrupt();
		} else {
			flushThread = new Thread() {
				public void run() {
					for (;;) {
						try {
							TimeUnit.SECONDS.sleep(60);
							flushContext();
						} catch (InterruptedException e) {
						}

					}

				}
			};
		}
		flushThread.start();
	}

}
